//
//  EWShoppingCartController.m
//  haveSomethingToEat
//
//  Created by 陈 宁权 on 2017/6/30.
//  Copyright © 2017年 陈 宁权. All rights reserved.
//

#import "EWShoppingCartController.h"
#import <UShareUI/UShareUI.h>
#import "EWShoppingHeaderView.h"
#import "EWMJDIYHeader.h"
#import "EWDishInfoCell.h"
#import "EWShopCartView.h"
#import "ThrowLineTool.h"
#import "ViewModel.h"
#import "EWPreOrderViewController.h"
#import "KxMenu.h"

@interface EWShoppingCartController ()<UISearchResultsUpdating,UITableViewDelegate,UITableViewDataSource,ThrowLineToolDelegate>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) EWShopCartView *shoppingCartView;
@property (nonatomic,strong) UISearchController *searchController;
@property (nonatomic,strong) NSMutableArray *dishesArr;
@property (nonatomic,strong) NSMutableArray *ordersArr;
//抛物线红点
@property (strong, nonatomic) UIImageView *redView;
@end

@implementation EWShoppingCartController
{
    UIImageView *navBarHairlineImageView;
}

/**
 *  抛物线小红点
 */
- (UIImageView *)redView
{
    if (!_redView) {
        _redView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
        _redView.image = [UIImage imageNamed:@"adddetail"];
        _redView.layer.cornerRadius = 10;
    }
    return _redView;
}

- (NSMutableArray *)dishesArr
{
    if (_dishesArr == nil) {
        _dishesArr = [NSMutableArray array];
    }
    return _dishesArr;
}

- (NSMutableArray *)ordersArr
{
    if (_ordersArr == nil) {
        _ordersArr = [NSMutableArray array];
    }
    return _ordersArr;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    navBarHairlineImageView.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    navBarHairlineImageView.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    //去掉导航栏下方的1px的线
    navBarHairlineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    //配置导航栏
    [self configNavigation];
    //配置tableView
    [self configTableView];
    //配置购物车
    [self configShopCartView];
    //配置添加购物车动画
    [ThrowLineTool sharedTool].delegate = self;
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(UpdatemainUI:) name:@"updateUI" object:nil];
    //设置下拉刷新控件
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    self.tableView.mj_header = header;
    [self.tableView.mj_header beginRefreshing];
}

- (void)configNavigation
{
    self.navigationItem.title = self.business.businessName;
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setImage:[UIImage imageNamed:@"more"] forState:UIControlStateNormal];
    rightBtn.frame = CGRectMake(0, 0, 30, 30);
    rightBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 7, 0, 0);
    [rightBtn addTarget:self action:@selector(more:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
}

- (void)configTableView
{
    CGRect tableViewFrame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, kScreenW, self.view.frame.size.height - 50);
    self.tableView = [[UITableView alloc] initWithFrame:tableViewFrame];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    
}

- (void)configShopCartView
{
    self.shoppingCartView  = [[EWShopCartView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 50, CGRectGetWidth(self.view.bounds), 50) inView:self.view];
    //点击购物车计算按钮
    __block typeof(self) bself = self;
    self.shoppingCartView.payBlock = ^{
        EWPreOrderViewController *preOrderVC = [[EWPreOrderViewController alloc] init];
        preOrderVC.orderList = bself.ordersArr;
        preOrderVC.businessInfo = bself.business;
        [bself.navigationController pushViewController:preOrderVC animated:YES];
    };
    
    [self.view addSubview:self.shoppingCartView];
}

- (void)headerRefresh
{
    [[BQUserDao shareObject] getDishesInfoListWithBusinessId:self.business.businessId andServiceReceiveResponseSuccess:^(id response) {
        _dishesArr = [EWDishInfo mj_objectArrayWithKeyValuesArray:response[@"dishesInfos"]];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        
    } ServiceReceiveResponseFailed:^(id response) {
        [self.tableView.mj_header endRefreshing];
        [SVProgressHUD showErrorWithStatus:response];
    }];
}

- (void)more:(UIButton *)sender
{
    NSArray *menuItems = @[
                           [KxMenuItem menuItem:@"店内搜索"
                                          image:[UIImage imageNamed:@"search"]
                                         target:self
                                         action:@selector(search)],
                           
                           [KxMenuItem menuItem:@"分享商家"
                                          image:[UIImage imageNamed:@"shares"]
                                         target:self
                                         action:@selector(shares)],
                           
                           [KxMenuItem menuItem:@"商家详情"
                                          image:[UIImage imageNamed:@"business"]
                                         target:self
                                         action:@selector(showBusinessInfo)],
                           
                           [KxMenuItem menuItem:@"收藏商家"
                                         image:[UIImage imageNamed:@"collection"]
                                        target:self
                                        action:@selector(collection)],
                           ];
    
    [KxMenu setTintColor:[UIColor whiteColor]];
    [KxMenu setTitleFont:[UIFont systemFontOfSize:17]];
    [KxMenu showMenuInView:self.navigationController
     .navigationBar.superview
                  fromRect:sender.frame
                 menuItems:menuItems];
}

- (void)search
{
    
}

- (void)shares
{
    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_QQ),@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_AlipaySession),@(UMSocialPlatformType_Sms)]];
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的platformType确定所选平台进行下一步操作
        
    }];
}

- (void)showBusinessInfo
{
    
}

- (void)collection
{
    
}

- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}


#pragma mark tableview代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dishesArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    EWDishInfoCell *cell = [EWDishInfoCell cellWithTableView:tableView];
    cell.dishInfo = self.dishesArr[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    __weak __typeof(&*cell)weakCell =cell;
    __block __typeof(self)bself = self;
    cell.plusBlock = ^(NSInteger count, BOOL animated) {//第一个参数是购物车添加该商品的数量，第二个参数是否需要动画
        /**
         *   给当前选中商品添加一个数量
         */
        EWDishInfo *dishInfo = self.dishesArr[indexPath.row];
        dishInfo.orderCount = count;
        /**
         *  通过坐标转换得到抛物线的起点和终点
         */
        CGRect parentRectA = [weakCell convertRect:weakCell.addShopCart.frame toView:self.view];
        CGRect parentRectB = [self.shoppingCartView convertRect:self.shoppingCartView.shoppingCartBtn.frame toView:self.view];
        /**
         *  是否执行添加的动画
         */
        if (animated) {
            [bself.view addSubview:self.redView];
            [[ThrowLineTool sharedTool] throwObject:self.redView from:parentRectA.origin to:parentRectB.origin];
            bself.ordersArr = [ViewModel storeOrders:dishInfo OrderData:self.ordersArr isAdded:YES];
        } else{
            bself.ordersArr = [ViewModel storeOrders:dishInfo OrderData:self.ordersArr isAdded:NO];
        }
        
        bself.shoppingCartView.OrderList.objects = self.ordersArr;
        [bself.shoppingCartView updateFrame:self.shoppingCartView.OrderList];
        [bself.shoppingCartView.OrderList.tableView reloadData];
        bself.shoppingCartView.badgeValue =  [ViewModel CountOthersWithorderData:self.ordersArr];
        double price = [ViewModel GetTotalPrice:bself.ordersArr];
        [bself.shoppingCartView setTotalMoney:price];
        
    };
    
    
    return cell;
}

#pragma mark - 设置购物车动画
- (void)animationDidFinish
{
    [self.redView removeFromSuperview];
    [UIView animateWithDuration:0.1 animations:^{
        self.shoppingCartView.shoppingCartBtn.transform = CGAffineTransformMakeScale(0.8, 0.8);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.1 animations:^{
            self.shoppingCartView.shoppingCartBtn.transform = CGAffineTransformMakeScale(1, 1);
        } completion:^(BOOL finished) {
            
        }];
        
    }];
}

#pragma mark - 通知更新
-(void)UpdatemainUI:(NSNotification *)Notification{
    
    NSMutableDictionary *dic =[NSMutableDictionary dictionaryWithDictionary: Notification.userInfo];
    //重新计算订单数组。
    self.ordersArr = [ViewModel storeOrders:dic[@"update"] OrderData:self.ordersArr isAdded:[dic[@"isAdd"] boolValue]];
    self.shoppingCartView.OrderList.objects = self.ordersArr;
    //设置高度。
    [self.shoppingCartView updateFrame:self.shoppingCartView.OrderList];
    [self.shoppingCartView.OrderList.tableView reloadData];
    //设置数量、价格
    self.shoppingCartView.badgeValue =  [ViewModel CountOthersWithorderData:self.ordersArr];
    double price = [ViewModel GetTotalPrice:self.ordersArr];
    [self.shoppingCartView setTotalMoney:price];
    //重新设置数据源
    self.dishesArr = [ViewModel UpdateArray:self.dishesArr atSelectDictionary:dic[@"update"]];
    [self.tableView reloadData];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}


#pragma mark searchController代理方法
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
